<?php
    //获取前段输入的数据
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $cpassword = trim($_POST['cpassword']);
    $sex = $_POST['sex'];   //1 or 0
    $email = $_POST['email'];
    $fav = @implode(',', $_POST['fav']);
    $source = $_POST['source'];
    $page = $_POST['page'];

    //！！！必要验证操作
    //用户名验证【可删】
    if(!strlen($username)){
        echo "<script>alert('用户名必须要填写');history.back()</script>";    //history.back返回上一级
        exit;
    } else if(!preg_match("/^[a-zA-Z0-9]{3,10}$/", $username)) {
        echo "<script>alert('输入的用户名不符合规范');history.back()</script>";
        exit;
    }
    //验证密码
    if(!empty($password)){
        //前后密码
        if($password != $cpassword){
            echo "<script>alert('两次输入的密码不相同');history.back()</script>";
            exit;
        } else if(!preg_match("/^[a-zA-Z0-9_*]{6,10}$/", $password)) {
            echo "<script>alert('密码填写不符合规范');history.back()</script>";
            exit;
        }
    }
    //验证邮箱
    if(!empty($email)){
        if(!preg_match("/^[a-zA-Z0-9_\-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/",$email)){
            echo "<script>alert('邮箱不符合规范');history.back()</script>";
            exit;
        }
    }
    include 'connect.php'; //连接数据库
    if($password) {
        $sql = "update info set password = '".md5($password)."', sex = '$sex', email = '$email', fav = '$fav' where username = '$username'";
        $url = 'logout.php';
        echo "密码输入错误";
    }
    else {
        $sql = "update info set sex = '$sex', email = '$email', fav = '$fav' where username = '$username'";
        $url = 'index.php';
    }
    if($source == 'admin') {
        $url = 'admin.php?&id=5&page='.$page;
    }
    $result = mysqli_query($conn, $sql);
    if($result){
        echo "<script>alert('更新个人资料成功');location.href='$url'; </script>";
    } else {
        echo "<script>alert('更新失败');history.back()</script>";
    }